#include "X264EncoderImpl.h"
#include "videoencodetask.h"
#include "capturetaskpack.h"
#include "convert.h"
#include "avpacket.h"
#include "rgbimage.h"
#include "string.h"

VideoEncodeTask::VideoEncodeTask()
{
    m_videoEncoder = NULL;
}

VideoEncodeTask::~VideoEncodeTask()
{
    close();
}
bool VideoEncodeTask::init(unsigned int width, unsigned int height, unsigned int kbps, unsigned int fps)
{
    if(!m_videoEncoder)
    {
        m_videoEncoder = new X264EncoderImpl;       //X264 编码实现
        if(m_videoEncoder)
        {
			m_videoEncoder->init(width, height, kbps, fps);
            return true ;
        }
    }
    return false;
}

string VideoEncodeTask::getX264Header()
{
    if(m_videoEncoder)
        return m_videoEncoder->get_x264_header();

    return string("");
}

string VideoEncodeTask::getX264SeiInfo()
{
    if(m_videoEncoder)
        return m_videoEncoder->get_x264_seiInfo();

    return string("");
}

float VideoEncodeTask::getFrameDuration()
{
    if(m_videoEncoder)
       return m_videoEncoder->getFrameDuration();

    return -1;
}

int VideoEncodeTask::close()
{
    std::string str("");

    int nthread  =thr_count();

    for (int i =0 ;i<nthread ;i++)
        putq(str);

    wait();

	if (m_videoEncoder)
	{
		m_videoEncoder->fini();
		delete m_videoEncoder;
		m_videoEncoder = NULL;
	}
    return true;
}

bool VideoEncodeTask::receive_handler(const char *data, int size)
{
    putq(std::string(data,size));
    return true;
}

int VideoEncodeTask::svc()
{
    if(m_videoEncoder)
    {
        std::string str ="";
        ColorSpaceConversions Conversions;
         while(getq(str))
         {
             if (str=="") break;

             CAPTURE_TASK_PACK   *task_pack = (CAPTURE_TASK_PACK   *)str.data();
             AVPacket            *packet = task_pack->packet;			//
             char                *image  = task_pack->buf;

             if(task_pack->len != task_pack->hight*task_pack->width*3/2)
             {
                packet->data.clear();
                packet->has_encoded = true ;   //编码视频帧完成
                int A  =0;
             }else
             {
                 if(m_videoEncoder->encode((unsigned char*)image,packet->data,5) == 0)//5用在有B帧的时候
                 {
                     packet->has_encoded = true ;   //编码视频帧完成
                 }
                  packet->has_encoded = true ;   //编码视频帧完成
             }
              delete []image;
         }
    }
    return 0;
}

